package com.cykj.service.impl;


import com.cykj.dto.ResponseDTO;

import com.cykj.entity.CyOrderDO;
import com.cykj.mapper.OrderMapper;
import com.cykj.mqEvent.CancelOrderEvent;
import com.cykj.service.IOrderService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public ResponseDTO buy(Integer userId, Integer goodId, Integer count) {
        // 如果购买量为零要阻止
        if (count<=0){
            return ResponseDTO.error("非法购买数量");
        }
        // 判断是否存在
        if (!redisTemplate.hasKey("stock:" + goodId)) {
            return ResponseDTO.error("商品不存在");
        }
        // 获取库存
        int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("stock:" + goodId)));
        // 判断库存
        if (stock < count) {
            return ResponseDTO.error("库存不足");
        }
        // 减库存
        redisTemplate.opsForValue().decrement("stock:" + goodId, count);
        // 创建CyOrder 对象
        CyOrderDO cyOrderDO = new CyOrderDO();
        cyOrderDO.setGoodId(goodId);
        cyOrderDO.setUserId(userId);
        cyOrderDO.setBuyCount(count);
        // 生成订单
        int re = orderMapper.insertOrder(cyOrderDO);
        // 发送延时消息
        CancelOrderEvent cancelOrderEvent = new CancelOrderEvent(cyOrderDO.getId());
        GenericMessage<CancelOrderEvent> message = new GenericMessage<>(cancelOrderEvent);
        sendOrderMessage(userId,message);
        // 可以买
        return re > 0
                ? ResponseDTO.success("购买成功")
                : ResponseDTO.error("购买失败");
    }

    // 异步发送订单消息
    public void sendOrderMessage(Integer userId, Message<?> message) {
        // 消息发送的主题
        String topic = "cancel-order";
        // 异步发送消息
        rocketMQTemplate.asyncSend(
                topic,      // 消息主题
                message,    // 消息内容
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        // 发送成功处理
                        System.out.println("用户ID为" + userId + "的订单消息发送成功，消息ID：" + sendResult.getMsgId());
                    }
                    @Override
                    public void onException(Throwable throwable) {
                        // 发送失败处理
                        System.err.println("用户ID为" + userId + "的订单消息发送失败：" + throwable.getMessage());
                        throwable.printStackTrace();
                    }
                },
                1000,  // 超时时间 1s
                3     // 延迟级别 3级 --> 10s
        );
    }
}
